package com.nullpointer.xchatfinal.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import com.nullpointer.xchatfinal.utils.AppNotificationManager;

public class AppNotification extends BroadcastReceiver {
	private final int NOTIFICATION_ID = 3002;

	@SuppressWarnings("deprecation")
	public void notify(Context context, String notificationMessage,
			String className) {
		NotificationManager notificationManager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
		Notification notification = new Notification(
				context.getApplicationInfo().icon, notificationMessage,
				System.currentTimeMillis());
		Intent notificationIntent = new Intent(
				android.content.Intent.ACTION_VIEW);
		String pkg = context.getApplicationContext().getPackageName();
		String cls = pkg + "." + className;
		notificationIntent.setComponent(new ComponentName(pkg, cls));
		notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_SINGLE_TOP);

		PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
				notificationIntent, 0);
		notification.setLatestEventInfo(context, getApplicationName(context),
				notificationMessage, pendingIntent);
		notification.flags = Notification.DEFAULT_LIGHTS
				| Notification.FLAG_AUTO_CANCEL;
		notificationManager.notify(NOTIFICATION_ID, notification);
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		Bundle bundle = intent.getExtras();
		String notificationMessage = bundle
				.getString(AppNotificationManager.NOTIFICATION_MESSAGE);
		String className = bundle.getString(AppNotificationManager.NAME_CLASS);
		notify(context, notificationMessage, className);
	}

	private static String getApplicationName(Context context) {
		int stringId = context.getApplicationInfo().labelRes;
		return context.getString(stringId);
	}
}
